package com.haois.mp.database.module.offaccounts.rest;


import com.google.gson.Gson;
import com.haois.mp.database.commom.enums.ApiResultEnum;
import com.haois.mp.database.exception.ErrorException;
import me.chanjar.weixin.common.exception.WxErrorException;
import com.haois.mp.database.module.basic.controller.BaseController;
import com.haois.mp.database.commom.enums.MpTypeEnum;

import com.haois.mp.database.module.common.daomain.UserToken;
import com.haois.mp.database.module.remote.service.IUserService;
import com.haois.mp.database.module.wxserver.util.MapUtil;
import com.haois.mp.database.module.common.service.IUserTokenService;
import com.haois.mp.database.util.jx.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wxmp/rest/user")
public class UserRestController extends BaseController {

    private static final Logger logger = LoggerFactory
            .getLogger(UserRestController.class);

    @Autowired
    private IUserService iUserService;
    @Autowired
    private IUserTokenService iUserTokenService;

    private Gson gson = new Gson();

    @RequestMapping("/getInfo")
    public String getInfo(HttpServletRequest request, String memberNum, String oid)
            throws RuntimeException, WxErrorException, ErrorException {
        String access_token = (String) request.getAttribute("access_token");
        Map userInfo = null;
        if (StringUtils.isNotBlank(memberNum)) {
            userInfo = iUserService.getUserInfo(access_token, memberNum, oid);
        } else if (StringUtils.isNotEmpty(oid)) {
            userInfo = iUserService.getUserInfo(access_token, oid);
        } else {
            userInfo = iUserService.getUserInfo(access_token);
        }
        return gson.toJson(userInfo);
    }

    @RequestMapping("/getHisInfo")
    public String getHisInfo(HttpServletRequest request, String memberNum, String oid)
            throws RuntimeException, WxErrorException, ErrorException {
        String access_token = (String) request.getAttribute("access_token");
        Map userInfo = iUserService.getUserInfo(access_token, memberNum, oid);
        return gson.toJson(userInfo);
    }

    @RequestMapping(value = "/updateInfo", method = RequestMethod.POST)
    public Map updateInfo(String name, String wechat, String email, String birthday, String introduce, String sex,
                          String addr, String mobiles, String tel, HttpServletRequest request) throws
            RuntimeException, WxErrorException, ErrorException {
        Map params = new HashMap();
        params.put("name", name);
        params.put("weChat", wechat);
        params.put("email", email);
        params.put("birthday", birthday);
        params.put("introduce", introduce);
        params.put("sex", StringUtils.isEmpty(sex) ? "1" : sex);
        params.put("site", addr);
        params.put("mobiles", mobiles);
        params.put("tel", tel);
        String access_token = (String) request.getAttribute("access_token");
        Map map = iUserService.updateUserInfo(params, access_token);
        return map;
    }


    /**
     * 用户注册
     *
     * @param memberNum 编号
     * @param password  密码（已加密）
     * @param vCode     验证码
     * @return
     * @throws RuntimeException
     */
    @RequestMapping("/register")
    public Map<String, Object> register(
            @RequestParam(value = "memberNum") String memberNum,
            @RequestParam(value = "password") String password,
            @RequestParam(value = "vCode") String vCode)
            throws RuntimeException {
        if (iUserService.loginApi(memberNum, vCode)) {
            return iUserService.register(memberNum, password, vCode);
        } else {
            return MapUtil.createMap(ApiResultEnum.API_10.getCode(), "验证码不正确");
        }
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Map loginAsync(
            @RequestParam(value = "username", required = true) String username,
            @RequestParam(value = "password", required = false) String password,
            @RequestParam(value = "url", required = false) String url,
            HttpServletRequest request) throws RuntimeException {
        String code = request.getParameter("code");
        String openId = wxOAuth2AccessTokenUtil.getOpenid(code, request);
        Map<String, Object> result = new HashMap<>();
        if (StringUtils.isNotEmpty(openId)) {

            if (!iUserService.loginApi(username, password)) {
                result.put("code", "01");
                result.put("msg", "手机号码应使用验证码登录");
                return result;
            }
            result = iUserService.login(username, password, openId, MpTypeEnum.OFFACCOUNTS.getType(), null);
            if ("00".equals(result.get("code")) || "05".equals(result.get("code"))) {
                UserToken userToken = iUserTokenService.findByOpenId(openId, MpTypeEnum.OFFACCOUNTS.getType());
                String access_token = (String) result.get("data");
                //只允许一对一的绑定
                UserToken oldUt = iUserTokenService.findByUserId(username, MpTypeEnum.OFFACCOUNTS.getType());
                if (oldUt != null && !openId.equals(oldUt.getOpenId())) {
                    iUserTokenService.logout(oldUt.getOpenId(), MpTypeEnum.OFFACCOUNTS.getType(), "绑定微信用户[" + openId + "]");
                }
                if (userToken == null) {
                    userToken = new UserToken(username, openId, access_token);
                    userToken.setCreateTime(DateUtil.getYMdHm());
                    iUserTokenService.login(userToken);
                } else {
                    //else 条件正常不会执行到
                    iUserTokenService.saveUserTokenHis(userToken, "重新登录", MpTypeEnum.OFFACCOUNTS.getType());
                    userToken.setAccessToken(access_token);
                    userToken.setUserId(username);
                    userToken.setUpdateTime(DateUtil.getYMdHm());
                    iUserTokenService.updateInfo(userToken);
                }
            }
        } else {
            result.put("code", "01");
            result.put("msg", "微信公众号授权失败,请稍候再试");
        }
        return result;

    }

    /**
     * 修改头像
     *
     * @param request
     * @param media_id 微信上传的头像地址
     * @return
     */
    @RequestMapping(value = "/userPhoto", method = RequestMethod.POST)
    public Map updateUserPhoto(HttpServletRequest request, String media_id) throws WxErrorException {
        try {
            String access_token = (String) request.getAttribute("access_token");
            logger.info("上传到微信的图片mediaId为:[{}]", media_id);
            File file = wxMpService.getMaterialService().mediaDownload(media_id);
            Map map = iUserService.modifyPhoto(file, access_token);
            return map;
        } catch (Exception e) {
            logger.error(e.getMessage());
            Map errMap = new HashMap();
            errMap.put("code", "10");
            errMap.put("msg", "上传头像异常,请稍后再试");
            return errMap;
        }
    }

    /**
     * 发送用户注册验证码
     *
     * @param phoneNumber 电话号码
     * @param request
     * @param response
     * @return
     * @throws RuntimeException
     */
    @RequestMapping("/sendCode")
    public Map sendVerifyCode(
            @RequestParam(value = "phoneNumber") String phoneNumber,
            HttpServletRequest request, HttpServletResponse response)
            throws RuntimeException {
        return iUserService.sendVerifyCode(phoneNumber);
    }

    /**
     * 重置密码
     *
     * @param phoneNumber 电话
     * @param code        验证码
     * @param newPassword 新的密码
     * @param request
     * @return
     */
    @RequestMapping(value = "/reset/password", method = RequestMethod.POST)
    public Map forgetPSW(@RequestParam("phoneNumber") String phoneNumber,
                         @RequestParam("code") String code,
                         @RequestParam("newPassword") String newPassword, HttpServletRequest request) throws WxErrorException {
        String access_token = (String) request.getAttribute("access_token");

        Map result = iUserService.resetUserPassword(access_token, code, newPassword, phoneNumber);
        return result;
    }

    /**
     * 重置密码发送验证码
     *
     * @param phoneNumber 电话
     * @param request
     * @return
     */
    @RequestMapping(value = "/reset/verifyCode", method = RequestMethod.POST)
    public Map resetPassVerifyCode(@RequestParam("phoneNumber") String phoneNumber, HttpServletRequest request) throws WxErrorException {
        logger.debug("发重置密码验证码......");
        String access_token = (String) request.getAttribute("access_token");
        Map result = iUserService.sendResetPassVerifyCode(phoneNumber, access_token);
        return result;
    }


}
